package com.xhwl.centiotdata.suppliersystem.dahua;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.handler.visitor.impl.VisitorIntegrationDaHuaHandler;
import com.xhwl.centiotdata.pojo.constant.DaHuaConstant;
import com.xhwl.centiotdata.pojo.dto.dahua.IdentityDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.dahua.PedestrianRecordDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.dahua.UserDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.dahua.VisitorInfoDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.visitor.VisitorIntegrationConfigDTO;
import com.xhwl.centiotdata.utils.Base64Utils;
import com.xhwl.common.dto.cent.sdata.AccountDTO;
import com.xhwl.common.dto.cent.visitor.VisitorAuthDTO;
import com.xhwl.common.dto.cent.visitor.VisitorInfoDTO;
import com.xhwl.common.dto.cent.visitor.VisitorQrCodeDTO;
import com.xhwl.common.enums.CodeEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.auth.AuthAccountMapping;
import com.xhwl.common.pojo.cent.sdata.Account;
import com.xhwl.common.query.cent.visitor.VisitorPrivilegeDeviceQuery;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Author: yanyixiong
 * @Description:
 * @Date: create in 15:05 2022/3/4
 */
@Slf4j
@Service
public class VisitorDaHuaHandler {

    @Autowired
    private GeneralDaHuaHandler generalDaHuaHandler;

    public List queryIdentity(VisitorIntegrationConfigDTO configDTO) {
        JSONObject resultObject = generalDaHuaHandler.get(DaHuaConstant.QUERY_IDENTITY_URL, null, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};errMsg:{}", DaHuaConstant.QUERY_IDENTITY_URL, resultObject.getString("errMsg"));
            throw new BusinessException(resultObject.getString("errMsg"));
        }

        return resultObject.getObject("data",List.class);
    }

    public Long createIdentity(VisitorIntegrationConfigDTO configDTO) {
        IdentityDaHuaDTO identityDaHuaDTO = IdentityDaHuaDTO.builder().name("普通员工").description("默认身份").build();
        Map<String,Object> params = JSONObject.parseObject(JSONObject.toJSONString(identityDaHuaDTO), Map.class);
        JSONObject resultObject = generalDaHuaHandler.post(DaHuaConstant.CREATE_IDENTITY_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaConstant.CREATE_IDENTITY_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            throw new BusinessException(resultObject.getString("errMsg"));
        }
        return resultObject.getLong("data");
    }

    public AuthAccountMapping createUser(VisitorIntegrationConfigDTO configDTO, UserDaHuaDTO userDaHuaDTO) {
        Map<String,Object> params = JSONObject.parseObject(JSONObject.toJSONString(userDaHuaDTO), Map.class);
        JSONObject resultObject = generalDaHuaHandler.post(DaHuaConstant.CREATE_USER_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaConstant.CREATE_USER_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            throw new BusinessException(resultObject.getString("errMsg"));
        }
        AuthAccountMapping authAccountMapping = new AuthAccountMapping();
        String data = resultObject.getString("data");
        authAccountMapping.setOpenId(data);
        authAccountMapping.setOpenCode(userDaHuaDTO.getCode());
        return authAccountMapping;
    }

    public AuthAccountMapping queryUser(Account account, VisitorIntegrationConfigDTO configDTO) {
        AuthAccountMapping authAccountMapping = null;
        HashMap<String, Object> params = new HashMap<>();
        params.put("phone",account.getPhone());
        params.put("pageNum",1);
        params.put("pageSize",10);
        JSONObject resultObject = generalDaHuaHandler.post(DaHuaConstant.QUERY_USER_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaConstant.QUERY_USER_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        JSONObject data = resultObject.getJSONObject("data");
        JSONArray pageData = data.getJSONArray("pageData");
        if(!pageData.isEmpty()){
            JSONObject object = (JSONObject) pageData.get(0);
            UserDaHuaDTO userDaHuaDTO = object.toJavaObject(UserDaHuaDTO.class);
            authAccountMapping = new AuthAccountMapping();
            authAccountMapping.setOpenId(userDaHuaDTO.getId());
            authAccountMapping.setOpenCode(userDaHuaDTO.getCode());
        }
        return authAccountMapping;

    }

    /**
     * 预约授权
     * @param configDTO
     * @param infoDTO
     * @return
     */
    public ResultJson createVisitorAuth(VisitorIntegrationConfigDTO configDTO, VisitorInfoDaHuaDTO infoDTO) {
        Map<String,Object> params = JSONObject.parseObject(JSONObject.toJSONString(infoDTO), Map.class);
        JSONObject resultObject = generalDaHuaHandler.post(DaHuaConstant.VISITOR_BOOK_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaConstant.VISITOR_BOOK_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return ResultJson.fail(resultObject.getString("errMsg"));
        }
        return ResultJson.success(CodeEnum.SUCCESS.description,resultObject.getString("data"));
    }

    /**
     * 下发二维码
     * @param configDTO
     * @return
     */
    public ResultJson getQrCode(VisitorIntegrationConfigDTO configDTO, VisitorAuthDTO visitorAuthDTO) {
        //大华二维码有效期暂定为当天晚上24点
        Date startDate = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = simpleDateFormat.format(startDate);
        String dateStr = startTime.split(" ")[0];
        String endTime = dateStr + " 23:59:59";
        HashMap<String, Object> params = new HashMap<>();
        params.put("type",1);
        params.put("personCode",visitorAuthDTO.getIntervieweeOpenCode());
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        params.put("channels",visitorAuthDTO.getOpenDeviceIdList());
        params.put("times",visitorAuthDTO.getTimes());
        params.put("faceFile", "data:image/jpeg;base64,"+Base64Utils.imageUrlToBase64(visitorAuthDTO.getFaceUrl()));

        JSONObject resultObject = generalDaHuaHandler.post(DaHuaConstant.QR_CODE_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaConstant.QR_CODE_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return ResultJson.fail(resultObject.getString("errMsg"));
        }
        return ResultJson.success(CodeEnum.SUCCESS.description,resultObject.getString("data"));
    }

}
